package com.atjinggu.jinggumail.coupon.service.impl;

import com.atjinggu.jinggumail.coupon.entity.SeckillSkuRelationEntity;
import com.atjinggu.jinggumail.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atjinggu.jinggumail.common.utils.PageUtils;
import com.atjinggu.jinggumail.common.utils.Query;

import com.atjinggu.jinggumail.coupon.dao.SeckillSessionDao;
import com.atjinggu.jinggumail.coupon.entity.SeckillSessionEntity;
import com.atjinggu.jinggumail.coupon.service.SeckillSessionService;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {

    @Autowired
    SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> list3DaysSeckillSku() {
        //封装近三天的日志 即2021-2-23 00:00:00 - 2021-2-25 59:59:59
        //活动开始时间在这三天内即可
        List<SeckillSessionEntity> entities = this.baseMapper.selectList(new QueryWrapper<SeckillSessionEntity>().between("start_time", getStart(), getEnd()));
        List<SeckillSessionEntity> collect = entities.stream().map(item -> {
            Long id = item.getId();
            List<SeckillSkuRelationEntity> sessions = seckillSkuRelationService.list(new QueryWrapper<SeckillSkuRelationEntity>().eq("promotion_session_id", id));
            item.setRelations(sessions);
            return item;
        }).collect(Collectors.toList());
        return collect;
    }

    private String getStart() {
        LocalDate now = LocalDate.now();
        LocalTime min = LocalTime.MIN;
        return  LocalDateTime.of(now, min).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    private String getEnd() {
        LocalDate now = LocalDate.now().plusDays(2);
        LocalTime max = LocalTime.MAX;
        return  LocalDateTime.of(now, max).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }


}